package com.tzb.gateway;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description TODO
 * @Author tzb
 * @Date 2021/1/11 19:29
 * @Version 1.0
 **/
@Configuration
public class KeyResolverConfiguration {

    /**
     * 基于请求路径的限流规则
     * // abc
     * // 基于ip 127.0.0.1
     * // 基于参数
     *
     * @return
     */
    //@Bean
    public KeyResolver pathKeyResolver() {

        // 自定义的KeyResolver
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getPath().toString());
            }
        };
    }

    /**
     * 基于请求参数的限流
     * 请求 abc？userId=1
     *
     * @return
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(
                // exchange.getRequest().getQueryParams().getFirst("userId")
                exchange.getRequest().getHeaders().getFirst("X-Forwarded-For")
        );
    }


}
